import { getStore, setStore } from "@/utils/store";
import { login, logout } from "@/api/user/login";
import { baseUrl } from "@/config/env";
import { Notify } from "vant";

const user = {
  state: {
    userInfo: getStore({ name: "userInfo" }) || {},
    token: getStore({ name: "token" }) || "",
  },
  actions: {
    Login({ commit }, userInfo = {}) {
      return new Promise((resolve, reject) => {
        login({ number: userInfo.number, password: userInfo.password }).then(
          (res) => {
            if (res.data.code === 400) {
              Notify({
                type: "danger",
                duration: 1000,
                message: res.data.message,
              });
            } else if (res.data.code === 200) {
              const data = res.data.data;
              console.log(res);
              const token = data.token;
              const userInfo = {
                id: data.id,
                name: data.name,
                number: data.number,
                photo: baseUrl + "/" + data.photo,
                type: data.type,
              };

              commit("SET_TOKEN", token);
              commit("SET_USERIFNO", userInfo);
              resolve();
            } else {
              reject(res.data.message);
            }
          }
        );
      });
    },
    // 退出登入
    LogOut({ commit }) {
      return new Promise((resolve, reject) => {
        logout()
          .then(() => {
            commit("SET_TOKEN", "");
            commit("SET_USERIFNO", {});
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      // setToken(token)
      state.token = token;
      setStore({ name: "token", content: state.token });
    },
    SET_USERIFNO: (state, userInfo) => {
      state.userInfo = userInfo;
      setStore({ name: "userInfo", content: state.userInfo });
    },
  },
};

export default user;
